package com.xpc.starter.aspect;

import com.xpc.starter.annotation.DataPermission;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 功能描述：切面代理
 *
 * @author xpc on 2024/5/23 8:35
 */
@Component
@Aspect
@Slf4j
public class DataPermissionAspect {

//    public static final ThreadLocal<Method> threadLocal = ThreadLocal.withInitial(() -> null);
    public static final ThreadLocal<DataPermission> threadLocalDataPermission = ThreadLocal.withInitial(() -> null);

    @Pointcut("@annotation(com.xpc.starter.annotation.DataPermission) || @within(com.xpc.starter.annotation.DataPermission)")
    public void dataPermissionPointCut() {
    }

    @Before("dataPermissionPointCut()")
    public void controllerBefore(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        log.info("{} before ...... ", signature.getMethod().getName());
//        threadLocal.set(signature.getMethod());

        // 类上标注的注解
        DataPermission classAnnotation = joinPoint.getTarget().getClass().getAnnotation(DataPermission.class);
        // 获取方法上的注解
        DataPermission methodAnnotation = signature.getMethod().getAnnotation(DataPermission.class);
        // 如果方法上没有注解，则取类上的注解
        threadLocalDataPermission.set(methodAnnotation != null ? methodAnnotation : classAnnotation);
    }
}
